package com.itheima.sky.service.impl;

import com.itheima.sky.dao.EmployeeMapper;
import com.itheima.sky.entity.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.sky.common.R;

import com.itheima.sky.pojo.Employee;
import com.itheima.sky.service.EmployeeService;
import com.itheima.sky.utils.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class EmployeeServiceImpl implements EmployeeService{




    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public R<Employee> login(Employee employee) {
        return null;
    }


    @Override
    public void save(Employee employee) {
        //1. 补全密码，状态，创建、修改时间
//        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setPassword("123456");
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //2. 把数据交给mapper插入
        employeeMapper.save(employee);
    }



    /**
     * 作用： 员工列表分页
     *
     * @param page     当前页
     * @param pageSize 页面大小
     * @param name     用户名
     * @return
     */
    @Override
    public Page<Employee> findByPage(Integer page, Integer pageSize, String name) {
        //1. 设置当前页与页面大小
        PageHelper.startPage(page,pageSize);

        //2. 查询数据
        List<Employee> employeeList = employeeMapper.findByName(name);

        //3. 创建PageINfo对象，把list集合传入
        PageInfo<Employee> pageInfo = new PageInfo(employeeList);

        //4. 把pageinfo的信息转移到Page对象
        Page<Employee> pageResult = new Page<>(pageInfo.getList(),pageInfo.getTotal(),pageInfo.getPageSize(),pageInfo.getPageNum());


        return pageResult;
    }




    @Override
    public void update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employee);
    }



    @Override
    public R<Employee> findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        return R.success(employee);
    }

//jn


    @Override
    public Employee empLogin(String username, String password) {

        Employee emp = employeeMapper.findUser(username,password);
        if(emp==null){
            throw new BaseException("用户名或密码错误");
        }
        return emp;
    }
}
